<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="goodsRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="620"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="drawer-goods">
      <div class="goods-box">
        <div class="global-drawer-title">商品信息</div>
        <div class="box-form">
          <BasicForm @register="goodsForm" />
        </div>
      </div>
      <div class="goods-box">
        <div class="global-drawer-title">商品权限配置</div>
        <!-- <div class="auth-title">{{ authorityName }}</div> -->
        <div :class="drawerInfo.type === operateActionType.VIEW ? 'tree-list tree-view' : 'tree-list'">
          <a-tree
            defaultExpandAll
            blockNode
            v-model:checkedKeys="authTree.checkedKeys"
            @check="treeCheck"
            :checkable="checkable"
            :selectable="false"
            :tree-data="authTree.authTreeData"
            :fieldNames="{
              title: 'authorityName',
              key: 'authorityId'
            }"
            v-if="authTree.authTreeData.length"
          >
          </a-tree>
          <Empty v-if="!authTree.authTreeData.length"></Empty>
        </div>
      </div>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import Empty from '@/components/Empty/index.vue'
import { operateActionType } from '@/types/enum'
import { getUpdateSchemaArr } from '@/utils/formSchema'
import { numTransString, scrollToFirstError } from '@/utils'
import { getGoodsFormConfig } from '../dataSource'
import { message } from 'ant-design-vue'
import { toEleTreeData } from '@/utils'
import { cloneDeep } from 'lodash-es'
import api from '@/api'
import { ConsoleSqlOutlined } from '@ant-design/icons-vue'

const { goodsAdd, goodsUpdate } = api

const emit = defineEmits(['operateSuccess', 'register'])

const roleLoading = ref(false)

const drawerInfo = reactive<any>({
  type: '',
  record: {},
  originAuthority: []
})

const checkable = ref(false)
const authorityName = ref('')
const authTree = reactive<any>({
  checkedKeys: [],
  halfCheckedKeys: [],
  allLastKeys: [],
  authTreeData: []
})

const goodsFormConfig = getGoodsFormConfig()
const [goodsForm, { setFieldsValue, getFieldsValue, validate, resetFields, updateSchema }] = useForm(goodsFormConfig)

const [goodsRegister, { closeDrawer, changeOkLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  drawerInfo.record = cloneDeep(data.record) || {}
  drawerInfo.originAuthority = cloneDeep(data.originAuthority) || []

  if (data.type === operateActionType.VIEW) {
    checkable.value = false
  } else {
    checkable.value = true
  }
  if (data.authority && data.authority.length) {
    authorityName.value = data.authority[0].appName
    authTree.authTreeData = data.authority[0].authorityList
  }

  // 查看时表单展示
  updateSchema(getUpdateSchemaArr(goodsFormConfig.schemas, data.type))

  if (data.type !== operateActionType.ADD) {
    setFieldsValue({
      goodsName: drawerInfo.record.goodsName,
      goodsDesc: drawerInfo.record.goodsDesc
    })

    let authorityList = []
    let authorityIdSet = drawerInfo.record.authorityIdSet || []
    if (drawerInfo.originAuthority && drawerInfo.originAuthority[0].appName) {
      authorityList = cloneDeep(drawerInfo.originAuthority[0].authorityList) || []
    }

    // 编辑和查看时权限配置处理
    if (data.type === operateActionType.EDIT) {
      let checkedKeys: any[] = []
      let halfCheckedKeys: any[] = []
      if (authorityList && authorityList.length) {
        deepLastNode(data.authority[0].authorityList)
        authorityIdSet.forEach((item: any) => {
          if (authTree.allLastKeys.includes(item)) {
            checkedKeys.push(item)
          } else {
            halfCheckedKeys.push(item)
          }
        })
      }

      authTree.checkedKeys = checkedKeys
      authTree.halfCheckedKeys = halfCheckedKeys
    } else {
      let authTreeData: any[] = []
      authorityList.forEach((item: any) => {
        if (authorityIdSet.includes(item.authorityId)) {
          authTreeData.push(item)
        }
      })
      authTreeData = toEleTreeData(authTreeData)
      authTree.authTreeData = authTreeData
    }
  }
})

const deepLastNode = (data: any) => {
  data.map((item: any) => {
    if (item.children && item.children.length > 0) {
      deepLastNode(item.children)
    } else {
      authTree.allLastKeys.push(item.authorityId)
    }
  })
}

const drawerReset = () => {
  changeOkLoading(false)
  authTree.checkedKeys = []
  authTree.halfCheckedKeys = []
  authTree.allLastKeys = []
  authTree.authTreeData = []
  resetFields()
}

// 权限勾选赋值半节点
const treeCheck = (checkedKeys: any[], e: any) => {
  authTree.halfCheckedKeys = e.halfCheckedKeys
}
// 提交数据
const confirmSubmit = async () => {
  try {
    await validate()
    let authorityIdSet = [...authTree.checkedKeys, ...authTree.halfCheckedKeys]
    let formValue = getFieldsValue()
    // if (!authorityIdSet.length) {
    //   return message.warn('请选择商品权限配置')
    // }

    if (drawerInfo.type === operateActionType.ADD) {
      changeOkLoading(true)
      await goodsAdd({
        ...formValue,
        authorityIdSet
      })
    } else if (drawerInfo.type === operateActionType.EDIT) {
      authorityIdSet = [...authorityIdSet, ...drawerInfo.record.authorityIdSet]
      authorityIdSet = [...new Set(authorityIdSet)]

      // if (drawerInfo.record.authorityIdSet && drawerInfo.record.authorityIdSet.length) {
      //   if (drawerInfo.record.packageNameSet && drawerInfo.record.packageNameSet.length) {
      //     for (let i = 0; i < drawerInfo.record.authorityIdSet.length; i++) {
      //       if (!authorityIdSet.includes(drawerInfo.record.authorityIdSet[i])) {
      //         return message.warn('编辑时不能取消之前商品权限配置')
      //       }
      //     }
      //   }
      // }

      changeOkLoading(true)
      await goodsUpdate({
        ...formValue,
        authorityIdSet,
        id: drawerInfo.record.id
      })
    }
    message.success(drawerInfo.type === operateActionType.ADD ? '商品新增成功' : '商品编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>

<style lang="less" scoped>
.drawer-goods {
  padding-top: 14px;
  padding-bottom: 16px;
  .goods-box {
    .box-form {
      margin-top: 24px;
      margin-bottom: 24px;
    }
    .auth-title {
      font-size: 14px;
      font-weight: 600;
      color: #4aa353;
      line-height: 20px;
      padding: 20px 40px 16px;
      margin-bottom: 16px;
      border-bottom: 1px solid #e0e1e6;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        left: 55px;
        bottom: 0px;
        width: 40px;
        height: 4px;
        background: #4aa353;
        border-radius: 100px 100px 0px 0px;
      }
    }
    .tree-list {
      padding: 8px 32px;
      max-height: 360px;
      min-height: 140px;
      overflow: auto;
      position: relative;
      border: 1px solid #e0e1e6;
      border-top: none;
    }
    :deep(.tree-view) {
      .ant-tree-node-content-wrapper-open,
      .ant-tree-node-content-wrapper-close {
        .ant-tree-title {
          color: #cdcdcd;
        }
      }
      .ant-tree-node-content-wrapper-normal {
        position: relative;
        &::before {
          content: '';
          width: 7px;
          height: 11px;
          position: absolute;
          left: -12px;
          top: 5px;
          border: 2px solid @primary-color;
          border-top: 0;
          border-left: 0;
          transform: rotate(45deg);
          transform-origin: center;
        }
      }
    }
  }

  :deep(.ant-form-item-label) {
    font-weight: 600;
  }
}
</style>
